//
//  ClubStrategyListView.swift
//  ClubanGame
//
//  Created by Apple on 2024/8/13.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit

class ClubStrategyListView: UITableViewCell, RaeNetworkProtocol {

    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(8).mode(.scaleAspectFill).end()
    private let iconShadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#323233").font(14.font_semiBold).end()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#969799").font(12.font_regular).end()
    private let bottomLabel = c_make_ex(UILabel.self)
        .color("#969799").font(12.font_regular).end()
    let joinButton = c_make_ex(UIButton.self)
        .image("SquareList_follow")
        .image("SquareList_followed", state: .selected).end()
    
    var joinStrategy: ((_ md: ClubGameCommunityAllListModel) -> Void)?
    var todDetailVC: ((_ md: ClubGameCommunityAllListModel) -> Void)?
    
    var model: ClubGameCommunityAllListModel? {
        didSet{
            guard let md = model else { return }
            iconImageView.loadImage(url: md.icon)
            nameLabel.text = md.name
            let guanzhu = ClubGlobalTool.shared.formatNumber(num: md.guanzhu_num)
            subLabel.text = guanzhu + "用户已关注"
            if Int(md.news_num) ?? 0 > 0 {
                subLabel.text = guanzhu + "用户已关注" + "·" + md.news_num + "贴文"
            }
            bottomLabel.text = md.summary
            if md.is_bbs == 1 {
                joinButton.isSelected = true
            }else{
                joinButton.isSelected = md.is_guanzhu
            }            
        }
    }
    
    var gameModel: ClubNewHomeGameModel?{
        didSet{
            guard let md = gameModel else { return }
            iconImageView.loadImage(url: md.icon)
            nameLabel.text = md.name
            bottomLabel.text = md.summary
            joinButton.isSelected = true
        }
    }
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            iconImageView.subviews{
                iconShadowView
            }
            nameLabel
            subLabel
            bottomLabel
            joinButton
        }
                
        iconImageView.leading(12.0.Scale).top(4.0.Scale).size(60.0.Scale).bottom(16.0.Scale)
        iconShadowView.fillContainer()
        nameLabel.leading(84.0.Scale).trailing(90.0.Scale).top(6.0.Scale)
        subLabel.leading(84.0.Scale).trailing(90.0.Scale).top(29.0.Scale)
        bottomLabel.leading(84.0.Scale).trailing(90.0.Scale).top(48.0.Scale)
        joinButton.trailing(12.0.Scale).top(19.0.Scale).width(68.0.Scale).height(33.0.Scale)
        joinButton.addTarget(self, action: #selector(clickJoinButton), for: .touchUpInside)
    }
    
    @objc private func clickJoinButton(){
    
        guard let md = model  else { return }
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            if joinButton.isSelected {
                self.todDetailVC?(md)
            }else{
                Task{
                    let res = await network.request(.collectGoods(goodsId: md.id, type: "0"),isShowError: false)
                    if res.isSuccess {
                        joinButton.isSelected = true
                        subLabel.text = ClubGlobalTool.shared.calculateNumberInString(text: subLabel.text ?? "")
                        self.joinStrategy?(md)
                    }
                }
            }
        }else{
            if md.is_bbs == 1 && joinButton.isSelected {
                self.todDetailVC?(md)
            }else{
                UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }            
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

class ClubStrategyHistoryCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var models: [ClubGameCommunityAllListModel]? {
        didSet{
            collectionView.reloadData()
        }
    }
    
    var toDetailStrategyVC: ((_ md: ClubGameCommunityAllListModel) -> Void)?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            collectionView
        }
                
        collectionView.trailing(0).leading(12.0.Scale).top(0).bottom(0)
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 12
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 60.0.Scale, height: 80.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubStrategyHistoryItemCell.self, forCellWithReuseIdentifier: ClubStrategyHistoryItemCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubStrategyHistoryItemCell.description(), for: indexPath) as? ClubStrategyHistoryItemCell else { return UICollectionViewCell() }
        cell.model = models?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if let md = models?[indexPath.row] {
            toDetailStrategyVC?(md)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

class ClubStrategyHistoryItemCell: UICollectionViewCell {

    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(8).mode(.scaleAspectFill).end()
    private let iconShadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#323233").font(12.font_medium)
        .alignment(.center).end()
    
    var model: ClubGameCommunityAllListModel? {
        didSet{
            guard let md = model else { return }
            iconImageView.loadImage(url: md.icon)
            nameLabel.text = md.name
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            iconImageView.subviews{
                iconShadowView
            }
            nameLabel
        }
                
        iconImageView.leading(0).top(0).size(60.0.Scale)
        iconShadowView.fillContainer()
        nameLabel.leading(0).trailing(0)
        nameLabel.Top == iconImageView.Bottom
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

}

//MARK: 论坛列表topView
class ClubStrategyListTopView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {

    private let attentionImg = c_make_ex(UIImageView.self)
        .image("SquareList_myAttention").mode(.scaleAspectFill).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let moreButton = c_make_ex(UIButton.self)
        .image("Square_more").end()
    
    var sourceData: [ClubGameCommunityAllListModel]? {
        didSet{
            if sourceData?.count ?? 0 > 6 {
                moreButton.isHidden = false
            }else{
                moreButton.isHidden = true
            }
            collectionView.reloadData()
        }
    }
    var toStrategyDetailVC: ((_ model: ClubGameCommunityAllListModel) -> Void)?
    var moreBlock: ((_ datas: [ClubGameCommunityAllListModel]) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .white
        
        addSubview(attentionImg)
        addSubview(collectionView)
        addSubview(moreButton)
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 55.0.Scale, height: 75.0.Scale)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12.0.Scale, bottom: 0, right: 70.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubWuAttentionStrategyCell.self, forCellWithReuseIdentifier: ClubWuAttentionStrategyCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
        
        attentionImg.snp.makeConstraints { make in
            make.top.leading.bottom.equalToSuperview()
            make.width.equalTo(92.0.Scale)
        }
        collectionView.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.trailing.equalToSuperview().offset(-5.0.Scale)
            make.leading.equalToSuperview().offset(92.0.Scale)
        }
        moreButton.snp.makeConstraints { make in
            make.trailing.top.bottom.equalToSuperview()
            make.width.equalTo(75.0.Scale)
        }
    }
    
    @objc private func clickMoreButton(){
        guard let dataArr = sourceData else { return }
        moreBlock?(dataArr)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
       return sourceData?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubWuAttentionStrategyCell.description(), for: indexPath) as? ClubWuAttentionStrategyCell else { return UICollectionViewCell() }
        cell.model = sourceData?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [ClubGameCommunityAllListModel]()
        sourceData?.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        sourceData = models
        toStrategyDetailVC?(models[indexPath.row])
        
        collectionView.reloadData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


//MARK: 已关注论坛cell
class ClubWuAttentionStrategyCell: UICollectionViewCell {
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(8.0.Scale).end()
    private let selView = c_make_ex(UIView.self)
        .bgColor(.clear).corner(8.0.Scale).border("#FF7700", width: 1).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_medium).alignment(.center).end()
    
    var model: ClubGameCommunityAllListModel? {
        didSet{
            guard let md = model else { return }
            if md.isLocal {
                nameLabel.textColor = "#FF7700".toColor
                iconImageView.image = md.icon.toImage
            }else{
                nameLabel.textColor = "#7B7D80".toColor
                iconImageView.loadImage(url: md.icon)
            }
            nameLabel.text = md.name
            selView.isHidden = !md.isSel
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            selView
            iconImageView
            nameLabel
        }
        
        selView.top(0).leading(0).trailing(0).size(55.0.Scale)
        iconImageView.leading(3.0.Scale).trailing(3.0.Scale).top(3.0.Scale).size(48.0.Scale)
        nameLabel.leading(0).trailing(0)
        nameLabel.Top == iconImageView.Bottom + 4.0.Scale
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 分区titileView
class ClubStrategyTitleHeaderView: UITableViewHeaderFooterView {
         
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#1A1A1A").font(16.font_semiBold).end()
    let moreButton = c_make_ex(UIButton.self)
        .image("Square_list_more").end()
    
    var titleString: String? {
        didSet{
            guard let str = titleString else { return }
            nameLabel.text = str
        }
    }
    var isShowMore = false {
        didSet{
            moreButton.isHidden = !isShowMore
        }
    }
    
    var moreBlock: (() -> Void)?
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        addSubview(nameLabel)
        addSubview(moreButton)
        
        moreButton.isHidden = true
        
        nameLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12.0.Scale)
            make.top.equalToSuperview().offset(14.0.Scale)
        }
        moreButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview()
            make.width.height.equalTo(38.0.Scale)
            make.centerY.equalToSuperview()
        }
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
    }
    
    @objc private func clickMoreButton(){
        moreBlock?()
    }
        
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}
